package cn.edu.sysu.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.sysu.dao.IssueDao;
import cn.edu.sysu.dao.SolutionDao;
import cn.edu.sysu.dto.IssueDto;
import cn.edu.sysu.dto.UserDto;
import cn.edu.sysu.service.UserService;
import cn.edu.sysu.util.Transaction;
import cn.edu.sysu.util.TransactionRead;
import cn.edu.sysu.util.TransactionWrite;

public class LoadServlet extends HttpServlet {

	SolutionDao sDao = SolutionDao.INSTANCE;
	IssueDao iDao = IssueDao.INSTANCE;
	UserService uService = new UserService();

	Transaction read = TransactionRead.INSTANCE;
	Transaction write = TransactionWrite.INSTANCE;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String method = req.getParameter("method");

		if ("getAccessToken".equals(method)) {
			String email = req.getParameter("email");
			UserDto user;
			try {
				user = uService.getUserByEmail(email);
				if (user == null) {
					res.getWriter().print("{\"success\":0}");
				} else {
					res.getWriter().print(
							"{\"access_token\":\""
									+ user.getAccessToken()
									+ "\",\"success\":1, \"user\":"
									+ user.toJsonString()
									+ "}");
				}
				res.setContentType("text/JSON");

			} catch (SQLException e) {
				res.getWriter().print("{\"success\":0}");
				e.printStackTrace();
			}

		} else if ("saveIssue".equals(method)) {
			int solution_user_id = Integer.parseInt(req.getParameter("solution_user_id"));
			String issue = req.getParameter("issue");
			int problem_id = Integer.parseInt(req.getParameter("problem_id"));
			int revision = Integer.parseInt(req.getParameter("revision"));
			int issue_user_id = Integer.parseInt(req.getParameter("issue_user_id"));
			int reply_to = -1;
			if (req.getParameter("reply_to") != null) {
				reply_to = Integer.parseInt(req.getParameter("reply_to"));
			}

			IssueDto is = new IssueDto(solution_user_id, problem_id, revision, issue, issue_user_id, reply_to,
					new Date(System.currentTimeMillis()));
			System.out.println(is.getPost_time());
			iDao.saveIssue(write, is);
		}
	}
}
